import React, { useState, useRef, useEffect } from 'react';
import { Tabs, Button } from 'antd';
import orgCtrl from '@/ts/controller';
import { AppstoreAddOutlined } from '@ant-design/icons';
import { getResouces } from '@/config/location';
import NavigationBar from '../NavigationBar/newNav';
import { generateUuid } from '@/utils/excel';
import { ViewerHost } from '@/executor/open/page/view/ViewerHost';
import ViewerManager from '@/executor/open/page/view/ViewerManager';
import { IFile } from '@/ts/core';
import { IPageTemplate } from '@/ts/core/thing/standard/page';
import './index.less';
import { PortalTemplates, IPortalTemplates } from '../NavigationBar/pageTabManage';
import { NavigationItem } from '../types';
import { IMallTemplate } from '@/ts/core/thing/standard/page/mallTemplate';
import { MallTemplate } from '@/executor/open/mallTemplate/pages';
import { useFlagCmdEmitter } from '@/hooks/useCtrlUpdate';

const resource = getResouces();

const allPages: NavigationItem[] = [
  {
    key: 'workbench',
    label: '工作台',
    type: 'inner',
    backgroundImageUrl: `/img/${resource.location}/banner/workbench.png`,
    component: React.lazy(() => import('../Content/WorkBench/index')),
  },
  {
    key: 'activity',
    label: '动态',
    type: 'inner',
    backgroundImageUrl: `/img/${resource.location}/banner/groupactivity.png`,
    component: React.lazy(() => import('../Content/Activity/index')),
  },
];
const HomeNavTemplate: React.FC = () => {
  const [pages, setPages] = useState<any[]>([...allPages]);
  const [content, setContent] = useState<IFile[]>([]);
  const [portalManage, setPortalManage] = useState<IPortalTemplates>(
    new PortalTemplates(orgCtrl.user),
  );
  const [headData, setHeadData] = useState<any>([]);
  const [loading, setLoading] = useState(false);
  useFlagCmdEmitter('portalTemplate', async () => {
    initPage();
  });
  useEffect(() => {
    setContent([orgCtrl.user, ...orgCtrl.user.companys]);
    initPage();
  }, []);

  const initPage = async () => {
    setPortalManage(new PortalTemplates(orgCtrl.user));
    let res: any[] = (await orgCtrl.user.cacheObj.get('portalTemplate')) ?? [];
    if (res) {
      res.forEach((element: any) => {
        element.label = element.name;
        if (element.type == 5) {
          mapping(element);
        } else if (element.type == 1) {
          getPages(element);
        }
      });
      setPages([...allPages, ...res]);
      setHeadData(getTabItems([...allPages, ...res]));
    } else {
      setPages([...allPages]);
      setHeadData(getTabItems([...allPages]));
    }
    setLoading(true);
  };
  const mapping = (item: any) => {
    const navigation: NavigationItem = {
      id: item.id,
      belongId: item.belongId,
      key: generateUuid(),
      label: item.name,
      backgroundImageUrl: '',
      type: 'page',
      component: <div></div>,
    };
    return navigation;
  };
  const getPages = async (item: any) => {
    item.backgroundImageUrl = `/img/${resource.location}/banner/assetmodule.png`;
    item.component = React.lazy(() => import('../Content/AssetModule/index'));
    return item;
  };
  const getCompanyTemplate = async (item: IFile) => {
    if (item) {
      const templates: (IPageTemplate | IMallTemplate)[] = [];
      const targets = item.directory.target.targets;
      for (const target of targets) {
        templates.push(...(await target.directory.loadAllTemplate()));
      }
      return templates;
    }
    return [];
  };
  const getTemplatePages = async (
    item: IFile,
    belongId: string,
  ): Promise<IPageTemplate | IMallTemplate | null> => {
    const company = content.find((item) => item.id === belongId);
    if (company != undefined) {
      let templatePage = await getCompanyTemplate(company);
      let pages = templatePage.find((items) => items.id == item.metadata.id);
      if (pages != undefined) {
        return pages;
      }
      return null;
    } else {
      return null;
    }
  };
  const navRef = useRef(null);
  const setIsShowNav = (bol: boolean) => {
    navRef.current && navRef.current.showHideModal(true);
  };
  const getTabItems = (page: any = pages) => {
    return page.map((it: any) => {
      return {
        ...it,
        children:
          it.type == '5' || it.type == '6'
            ? it.component
            : React.createElement(it.component, {
                onChange: () => {
                  initPage();
                },
              }),
      };
    });
  };
  const getItem = (items: any[], key: string) => {
    return items.find((item) => item.key === key);
  };
  return loading ? (
    <>
      <Tabs
        items={headData}
        onChange={async (key) => {
          const index = getTabItems().findIndex((item: any) => item.key === key);
          sessionStorage.setItem('homePage', index);
          let res = getItem(getTabItems(), key);
          let pages: IPageTemplate | IMallTemplate | null = await getTemplatePages(
            res,
            res.belongId,
          );
          if (pages != null) {
            if (pages.typeName === '商城模板') {
              res.children = <MallTemplate current={pages as IMallTemplate} />;
            } else {
              res.children = (
                <ViewerHost
                  ctx={{
                    view: new ViewerManager(pages as IPageTemplate),
                  }}
                />
              );
              if (res.name === '资产看板') {
                res.children = <Board pages={pages as IPageTemplate} />;
              }
            }
            const index = headData.findIndex((item: any) => item.key === res.key);
            if (index !== -1) {
              const updatedItems = [...headData];
              updatedItems[index] = res;
              setHeadData(updatedItems);
            }
          }
        }}
        tabBarExtraContent={
          <Button
            type="text"
            icon={<AppstoreAddOutlined />}
            onClick={() => {
              setIsShowNav(true);
              portalManage.startEdit();
            }}>
            管理页面
          </Button>
        }></Tabs>
      <NavigationBar
        ref={navRef}
        list={allPages}
        portalManage={portalManage}
        onChange={() => {
          initPage();
        }}
      />
    </>
  ) : (
    <></>
  );
};

export default HomeNavTemplate;
